package org.linlinjava.litemall.wx.web;

/**
 * @author: weilai
 * @date: 2020/4/23
 * @description:
 */

import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.brand.dto.BrandVO;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallBrandCommentMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.db.util.BadWordUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 展示公司 公示信息...   评分信息   服务信息  热门.推介.
 */
@RestController
@RequestMapping("/wx/company")
@Validated
public class WxCompanyInfoController {
    private final Log logger = LogFactory.getLog(WxCompanyInfoController.class);
    //商品评论
    @Autowired
    private LitemallCommodityCommentService commodityCommentService;
    @Autowired
    private LitemallCommodityService commodityService;
    @Autowired
    private LitemallDisputeService disputeService;
    @Autowired
    private LitemallKeywordService keywordService;
    @Autowired
    private LitemallBrandAppendService brandAppendService;
    @Autowired
    private LitemallBrandService brandService;
    @Autowired
    private LitemallBrandGrandService brandGrandService;
    //本公司评论.霜林科技有限公司..id>>0
    @Resource
    LitemallBrandCommentMapper brandCommentMapper;
    @Autowired
    private LitemallBrandInfoService brandInfoService;

    /**
     * 查:根据关键词 :: 并集..以名字去commodityName 和描述commodityDescription中 查询
     * @param keyword
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/search")
    public Object findCategoryList(String keyword,
                                   @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "12") Integer limit) {
        //1.如果Keyword表不存在，存入数据库表，查询次数 count为.1
        if(!StringUtils.isEmpty(keyword)){
            LitemallKeyword KeywordLitemallByKeyword = keywordService.findOneByKeyword(keyword);
            if(null==KeywordLitemallByKeyword){
                logger.info("没有关键词进入>>>>>>收藏关键词");
                LitemallKeyword litemallKeyword = new LitemallKeyword();
                litemallKeyword.setKeyword(keyword);
                litemallKeyword.setCount(1);
                keywordService.add(litemallKeyword);}
            //2.Keyword 如果存在。查询次数 count+1
            else {
                System.out.println("有关键词。。。进入>>>>>>");
                LitemallKeyword oneByKeyword = keywordService.findOneByKeyword(keyword);
                oneByKeyword.setCount(oneByKeyword.getCount()+1);
                int i = keywordService.updateById(oneByKeyword);
                System.out.println("有关键词。查询数量+1》》》》" + i);}}
        //关键词作为:1name 2 描述DESC
       // 发送 "sort":"commodity_price"  倒序 "sort":"commodity_price desc"
        String sort = "commodity_price";
        PageInfo<LitemallCommodity> commodityListBLOBS = commodityService.findByL1L2L3(page,limit,null,
                null, null, null, keyword, sort);
        return ResponseUtil.ok(commodityListBLOBS);
    }

    /*是否热门*/
    @GetMapping("/hot")
    public Object isHotCommodity( @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "8") Integer limit){
        String isHot="热门";
        String marketing ="";
        Integer brandId = null ;
        PageInfo<LitemallCommodity> litemallCommodityPageInfo = commodityService.brandIdHotOrMarketing(brandId,page, limit, isHot, marketing);
        return ResponseUtil.ok(litemallCommodityPageInfo);
    }
    /*是否推介*/
    @GetMapping("/marketing")
    public Object marketingCommodity( @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "8") Integer limit){
        String isHot="";
        String marketing ="推介";
        Integer brandId = null ;
        PageInfo<LitemallCommodity> litemallCommodityPageInfo = commodityService.brandIdHotOrMarketing(brandId,page, limit, isHot, marketing);
        return ResponseUtil.ok(litemallCommodityPageInfo);
    }
    @GetMapping("/hotAndMarketing")
    public Object hotAndMarketing( @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "6") Integer limit) {
        String isHot="热门";
        String marketing ="推介";
        Integer brandId = null ;
        PageInfo<LitemallCommodity> litemallCommodityPageInfo = commodityService.brandIdHotOrMarketing(brandId,page, limit, isHot, marketing);
        return ResponseUtil.ok(litemallCommodityPageInfo);
    }

    /**
     * 公司的热门产品
     * @param brandId
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/commodityHot/{brandId}")
    public Object companyHotGoods(@PathVariable("brandId")Integer brandId, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "4") Integer limit) {
        System.out.println("brandId>>" +brandId);
        String isHot="热门";
        String marketing ="";
        PageInfo<LitemallCommodity> litemallCommodityPageInfo = commodityService.brandIdHotOrMarketing(brandId,page, limit, isHot, marketing);
        return ResponseUtil.ok(litemallCommodityPageInfo);
    }



    /**
     * discount降价折扣优惠大于 0显示
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/discount")
    public Object discountCommodity( @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "8") Integer limit){
        PageInfo<LitemallCommodity> litemallCommodityPageInfo = commodityService.discountCommodity(page,limit);
        return ResponseUtil.ok(litemallCommodityPageInfo);
    }

    /*查:本公司..商品详细介绍 默认显示4条*/
    @GetMapping("/allDetail/{brandId}")
    public Object allDetail(@PathVariable("brandId") Integer brandId,
                            @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "4") Integer limit){
        HashMap<String, String> searchMap = new HashMap<>();
        searchMap.put("brandId",String.valueOf(brandId));
        PageInfo<LitemallCommodity> litemallCommodityPageInfo = commodityService.findCommodityList(searchMap,page,limit);
        return ResponseUtil.ok(litemallCommodityPageInfo);
    }

    /*------------------------------------------------------*/
    //显示 公司 1名字 2图地址
    // LevelA..级别A.默认显示4张.点击更多显示8张..或4倍数
    @GetMapping("/brandPicA")
    public Object brandPicLevelA(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "4") Integer limit){
        String level= "A";
        PageInfo brandPictureListLevelA = brandService.findBrandLevelPictureList(level,page, limit);
        return ResponseUtil.ok(brandPictureListLevelA);
    }

    @GetMapping("/brandPicB")
    public Object brandPicLevelB(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "4") Integer limit){
        String level= "B";
        PageInfo brandPictureListLevelB = brandService.findBrandLevelPictureList(level,page, limit);
        return ResponseUtil.ok(brandPictureListLevelB);
    }

    private static final int PAGE_OF = 1;
    private static final int PAGEHIDE_OF = 6;
    /**
     *  新加入商城.显示
     *  实体类 brand  加字段(不在数据库)  private String newAdd; 前端返回的时间.不放入时分秒
     */
    @GetMapping("/newCompany")
    public Object newCompany(){
        Integer page = PAGE_OF;
        Integer pageSize = PAGEHIDE_OF;
        String sort ="add_time";
        String order="desc";
        List<LitemallBrand> brandList = brandService.findBrandList(page, pageSize, sort, order);
        for (LitemallBrand litemallBrand : brandList) {
            String addTimeSubString = litemallBrand.getAddTime().toString().substring(0, 10);
            litemallBrand.setNewAdd(addTimeSubString);
        }
        return ResponseUtil.okList(brandList);
    }

    //显示某个公司的详细信息
    @GetMapping("/detail/{brandId}")
    public Object companydetail(@PathVariable("brandId")Integer brandId){
        LitemallBrand brandOne = brandService.findById(brandId);
        BrandVO brandVO = new BrandVO();
        BeanUtils.copyProperties(brandOne,brandVO);
        return ResponseUtil.ok(brandVO);
    }

    /**
     * 公司的.证书
     * @param brandId
     * @return
     */
    @GetMapping("/credential/{brandId}")
    public Object credential(@PathVariable("brandId")Integer brandId) {
        List<LitemallBrandAppend> litemallBrandAppends = brandAppendService.credentialBybrandId(brandId);
        ArrayList<String> urls = new ArrayList<>();
        for (LitemallBrandAppend brandAppend : litemallBrandAppends) {
            urls.add(brandAppend.getPicUrl());
        }
        return ResponseUtil.okList(urls);
    }


    /*---------------------------------------------------*/
    //1.企业评分  共多少人评分, 5-1 分之间数量  ..和百分比...根据商户的产品.订单量显示
    //商品评论的数据 commodityCommentService
    @GetMapping("/reviewStar/{brandId}")
    public Object commentStar(@PathVariable("brandId") Integer brandId) {
        List<LitemallBrandGrand> brandGrandbyBrandId = brandGrandService.findByBrandId(brandId);
        Map<String,String> reMap=new HashMap<>();
        if(brandGrandbyBrandId.size()>0){
            for (LitemallBrandGrand brandGrand : brandGrandbyBrandId) {
          //      reMap.put(brandGrand.getStarLevel(),brandGrand.getBrandGrand());
            }
          return ResponseUtil.ok(reMap);
        }
        //没有分数
        reMap.put("total",String.valueOf(0));
        reMap.put("AVGPercentage",0.00 + "%");
        reMap.put("oneStarPercentage","0.00%");
        reMap.put("twoStarPercentage","0.00%");
        reMap.put("threeStarPercentage","0.00%");
        reMap.put("fourStarPercentage","0.00%");
        reMap.put("fiveStarPercentage","0.00%");
        return ResponseUtil.ok(reMap);
    }

    //2企业纠结退款率
    @GetMapping("/disputePercent/{brandId}")
    public Object disputePercent(@PathVariable("brandId") Integer brandId) {
        //商户ID....得到争议已完成 state320 单数
        Map<String,Object> map=new HashMap<>();
        List<LitemallDisputeOrder> litemallDisputeOrders = disputeService.byBrandId(brandId);
        //有争议单..则找争议单个数\
        if (litemallDisputeOrders.size() > 0) {
            BigDecimal dispute = new BigDecimal(litemallDisputeOrders.size());
            List<LitemallDisputeOrder> disputeOrders = disputeService.byBrandId320(brandId);
            BigDecimal dispute320 = new BigDecimal(disputeOrders.size());
            BigDecimal divideBD = dispute320.divide(dispute, 4, BigDecimal.ROUND_HALF_UP);
            map.put("dispute320",divideBD.multiply(new BigDecimal("100")).toString().substring(0,5) + "%");
            return ResponseUtil.ok(map);
        }
        map.put("dispute320",0.00 + "%");
        return ResponseUtil.ok(map);
    }

    //3企业半年评分
    @GetMapping("/halfYear/{brandId}")
    public Object  halfYearService(@PathVariable Integer brandId){
        //商户ID....得到商品ID
        Map<String,String> searchMap= new HashMap<>();
        searchMap.put("brandId",brandId.toString());
        Integer page =1;
        Integer limit =100;
        PageInfo<LitemallCommodity> commodityList = commodityService.findCommodityList(searchMap, page, limit);
        if(commodityList.getSize()>0){
            Set<Integer> commodityIdSet=new HashSet<>();//商品ID集合
            for (LitemallCommodity litemallCommodity : commodityList.getList()) {
                commodityIdSet.add(litemallCommodity.getId());
            }
            Integer oneStar = 0 ;
            Integer twoStar = 0 ;
            Integer threeStar = 0 ;
            Integer fourStar = 0 ;
            Integer fiveStar = 0 ;
            Integer totleStar = 0 ;
            for (Integer commodityId : commodityIdSet) {
                //当前时间 起点是前6 个月
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime beginTime=now.minusMonths(6);
                List<LitemallCommodityComment> litemallCommodityComments = commodityCommentService.byCommodityId(commodityId,beginTime,now);
                for (LitemallCommodityComment comment : litemallCommodityComments) {
                    //review..是5个星级
                    BigDecimal review = comment.getReview();
                    logger.info("review>>>" + review );
                    if(review.equals(new BigDecimal("1"))){ oneStar++;}
                    if(review.equals(new BigDecimal("2"))){twoStar++;}
                    if(review.equals(new BigDecimal("3"))){threeStar++;}
                    if(review.equals(new BigDecimal("4"))){fourStar++;}
                    if(review.equals(new BigDecimal("5"))){fiveStar++;}
                    totleStar=oneStar + twoStar +  threeStar +  fourStar + fiveStar;
                }
            }
            Map<String,Object> map=new HashMap<>();
            BigDecimal totleStarBigDecimal=new BigDecimal(totleStar);
            BigDecimal oneBD = new BigDecimal(oneStar);
            BigDecimal twoBD = new BigDecimal(twoStar);
            BigDecimal threeBD = new BigDecimal(threeStar);
            BigDecimal fourBD = new BigDecimal(fourStar);
            BigDecimal fiveBD = new BigDecimal(fiveStar);
            //如果总数大于0..才能求得 %
            if(totleStarBigDecimal.compareTo(BigDecimal.ZERO)>0){
                //均值 共计星数 /单数
                BigDecimal AVGPercentage= (
                        oneBD.multiply(new BigDecimal("1"))
                                .add(twoBD.multiply(new BigDecimal("2")))
                                .add(threeBD.multiply(new BigDecimal("3")))
                                .add(fourBD.multiply(new BigDecimal("4")))
                                .add(fiveBD.multiply(new BigDecimal("5")))
                )
                        .divide(totleStarBigDecimal, 4, BigDecimal.ROUND_HALF_UP);
                map.put("HalfYearServiceScore",AVGPercentage.toString().substring(0,3));
                map.put("halfYearService",halfYearAll());
            }else {
                //.multiply(new BigDecimal("100"))
                map.put("ServiceScoreSelf", 0.0 );
                map.put("HalfYearAVG",halfYearAll());
            }
            return ResponseUtil.ok(map);
        }
        return ResponseUtil.fail(502,"暂时没有找到该公司信息");
    }

    //4行业的平均分数
    private String halfYearAll(){
        List<LitemallCommodityComment> commodityComments = commodityCommentService.byCommodityId();
      if(  commodityComments.size() < 0 ){
          return null;
      }
        BigDecimal avgAll = new BigDecimal("0");
        Map<String,String> map=new HashMap<>();
        for (LitemallCommodityComment commodityComment : commodityComments) {
            BigDecimal review = commodityComment.getReview();
            avgAll= avgAll.add(review);
        }
        BigDecimal divide = avgAll.divide(new BigDecimal(commodityComments.size()), 1, BigDecimal.ROUND_HALF_UP);
          return divide.toString();
    }


  /*  //4企业30天内服务完成情况
    @GetMapping("/mouthService/{brandId}")
    public Object  mouthService(@PathVariable Integer brandId){
        commodityCommentService.selectById()
    }*/


    /**
     * 给 霜林科技  留言...本公司的brandId 设置 为 0
     * @param request
     * @param body
     * @return
     */
    @PostMapping("insertComment")
    public Object insertComment(HttpServletRequest request, @RequestBody String body) {
        System.out.println("body>>>>" + body);
        //霜林科技 本公司的 的公司ID.默认为0
        Integer brandId = 0;
        //评论详细内容  不能为空
        String comment = JacksonUtil.parseString(body, "comment");
        if(StringUtils.isEmpty(comment)){throw  new RuntimeException("留言不能为空");}
        //签名 是姓名 不能为空
        String signature = JacksonUtil.parseString(body, "signature");
        if(StringUtils.isEmpty(signature)){throw  new RuntimeException("姓名不能为空");}
        String mail = JacksonUtil.parseString(body, "mail");
        String remark = JacksonUtil.parseString(body, "remark");//备注
        if(StringUtils.isEmpty(signature)){throw  new RuntimeException("手机不能为空");}
        comment = BadWordUtil.replaceBadWord(comment, BadWordUtil.maxMatchType, "*");

        LitemallBrandComment brandComment = new LitemallBrandComment();
        brandComment.setBrandId(brandId);
        brandComment.setSignature(signature);//本公司的评论
        brandComment.setMail(mail);
        brandComment.setComment("留言给霜林科技:" + comment);
        brandComment.setRemark(remark);
        brandCommentMapper.insertSelective(brandComment);
        return ResponseUtil.ok();
    }



    @GetMapping("/b/{id}")
    public  Object allBrandGrand(@PathVariable Integer id){
     //   Map<String, BigDecimal> stringBigDecimalMap = commodityCommentService.selectInfoByCommodity(id);

     /*   //1.拿到所有商户的ID  从商户表中
        List<Integer> brandIds = brandService.brandIdList();
        Set<Integer> brandIdListSet = new HashSet<>(brandIds);

        //2拿到所有的商户分数表 的brand_id  set2
        Set<Integer> brandIdSet = brandGrandService.brandIdList();
        //1 减去2  得到 哪些商户ID没有 写入 得分表中
        brandIdListSet.removeAll(brandIdSet);
        brandIds.clear();
        brandIds.addAll(brandIdListSet);
        //行业均分 brand_id 为 1
        LitemallBrandGrand brandGrandAVG = new LitemallBrandGrand();
        brandGrandAVG.setBrandId(1);
        brandGrandService.addBrandGrand(brandGrandAVG);
        //其他企业ID进入循环
        for (Integer brandId : brandIds) {
            LitemallBrandGrand brandGrand = new LitemallBrandGrand();
            brandGrand.setBrandId(brandId);
            System.out.println(">>>>>" + brandGrand);
        //    brandGrandService.addBrandGrand(brandGrand);
        }*/

    //从订单表中找到 商品,从商品中
        //商品评论的数据 commodityCommentService
       // commodityCommentService.
        return ResponseUtil.ok();
    }





//如果没有在brand_grand商户分值表中.则默认为0



}
